package fy.form.listen.log;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.util.Calendar;

import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

import org.apache.commons.logging.LogFactory;

import fy.util.MyUtil;


import jxl.write.Label;

public class LogWriter {

	private static org.apache.commons.logging.Log log = LogFactory
			.getLog(LogWriter.class);

	public static synchronized void writeError(String path, long summaryId) {
		try {
			OutputStreamWriter osw = new OutputStreamWriter(
					new FileOutputStream(path, true), "utf-8");

			osw.write(String.valueOf(summaryId));
			osw.write("\n");
			osw.flush();
			osw.close();
		} catch (Exception e) {
			log.error("OA2HR插件，写错误日志异常", e);
		}
	}

	public static synchronized void writeLog(String path, String message) {
		WritableWorkbook workbook = null;
		WritableSheet sheet = null;
		try {
			File file = new File(path);

			if (!file.exists()) {
				workbook = Workbook.createWorkbook(file);
				sheet = workbook.createSheet("日志", 0);
				sheet.addCell(new Label(0, 0, "时间"));
				sheet.addCell(new Label(1, 0, "日志"));
			} else {
				try {
					workbook = Workbook.createWorkbook(file,
							Workbook.getWorkbook(file));
					sheet = workbook.getSheet(0);
				} catch (Exception e) {
					System.out.println(file.getParent());
					workbook = Workbook
							.createWorkbook(new File(file.getParent() + "/"
									+ MyUtil.getTodayDateStr() + " "
									+ Calendar.getInstance().getTimeInMillis()
									+ ".xls"));
					sheet = workbook.createSheet("日志", 0);
					sheet.addCell(new Label(0, 0, "时间"));
					sheet.addCell(new Label(1, 0, "日志"));
				}
			}
			int row = sheet.getRows();
			sheet.addCell(new Label(0, row, MyUtil.getNowStr()));
			sheet.addCell(new Label(1, row, message));

			workbook.write();

		} catch (Exception e) {
			e.printStackTrace();
			log.error("写错误日志异常", e);
		} finally {
			try {
				if (workbook != null)
					workbook.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	// class Writer{
	//
	// }

	public static void main(String[] args) {
		writeLog("E:/11/2013-06-02.xls", "测试测试测试测试111测试测试测试测试");
		System.out.println(MyUtil.getRealPath(LogWriter.class));
	}
}
